package com.flyme.module.base.provider.service.impl;

    import cn.hutool.core.collection.CollectionUtil;
    import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
    import com.flyme.common.core.constants.CommonConstants;
    import com.flyme.common.core.model.query.CriteriaQuery;
    import com.flyme.common.core.model.query.PagerInfo;
    import com.flyme.common.core.model.query.PqGrid;
    import com.flyme.common.core.utils.ApiAssert;
    import com.flyme.common.core.utils.ObjectUtils;
    import com.flyme.core.base.supper.entity.EntityMap;
    import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
    import com.flyme.module.base.client.dto.SysUserDto;
    import com.flyme.module.base.client.entity.SysBalance;
    import com.flyme.module.base.client.entity.SysCompany;
    import com.flyme.module.base.client.entity.SysUser;
    import com.flyme.module.base.client.entity.SystemAccount;
    import com.flyme.module.base.provider.mapper.SysUserMapper;
    import com.flyme.module.base.provider.service.*;
    import com.flyme.module.exam.provider.service.BusUserabilityService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.util.List;
    import java.util.Map;

/**
 * @author: zyf
 * @date: 2018/10/24 16:33
 * @description:
 */
    @Service
    @Transactional(rollbackFor = Exception.class)
    public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysAccountService accountService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysBalanceService balanceService;
    @Autowired
    private BusUserabilityService userabilityService;
    @Autowired
    private SysCompanyService companyService;

    /**
     * 依据登录名查询系统用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public SysUser findByUserName(String userName) {
    return getOne(q().eq("userName", userName).or().eq("mobile", userName));
    }


    /**
     * 依据手机号查询用户
     *
     * @param mobile
     * @return
     */
    @Override
    public SysUser findByMobile(String mobile) {
    return getOne(q().eq("mobile", mobile));
    }
    /**
     * 依据手机号查询用户
     *
     * @param mobile
     * @returnd
     */
    @Override
    public EntityMap findByUserId(Long userId) {
    CriteriaQuery queryWrapper = new CriteriaQuery<EntityMap>(new PagerInfo());
    queryWrapper.select("*");
    queryWrapper.eq("Id",userId);
    return  getEntityMap(queryWrapper);
    }



    /**
     * 删除用户
     *
     * @param userIds
     * @return
     */
    @Override
    public Boolean delByIds(Long[] userIds) {
    ApiAssert.notNull("参数不能为空", userIds);
    baseMapper.deleteBatchIds(CollectionUtil.toList(userIds));
    roleService.deleteByUserIds(userIds);
    return accountService.deleteByIds(userIds);
    }

    @Override
    public Boolean updateStatus(String id, int status) {
    UpdateWrapper user = new UpdateWrapper();
    return update(user.set(true, "status", status).eq(true, "id", id));
    }

    /**
     * 更新手机号
     */
    public boolean updateMobile(long userId, String oldmobile, String newmobile) {
    SystemAccount account = accountService.findByUser(userId, oldmobile);
    if (ObjectUtils.isNotEmpty(account)) {
    account.setAccount(newmobile);
    accountService.saveOrUpdate(account);
    }
    UpdateWrapper cw = new UpdateWrapper();
    return update(cw.set(true, "mobile", newmobile).eq(true, "id", userId));
    }

    /**
     * 更新用户融云token
     */
    public boolean updateRong(long userId, String rongToken) {
    UpdateWrapper cw = new UpdateWrapper();
    return update(cw.set(true, "rongToken", rongToken).eq(true, "id", userId));
    }

    /**
     * 7日注册统计
     */
    public List<EntityMap> getSevenSale(String userType) {
    EntityMap map = new EntityMap();
    map.put("userType", userType);
    return baseMapper.getSevenTotal(map);
    }

    @Override
    public List<Map<String, Object>> getSelectedUser(String userType, String userIds) {
    return listMaps(q().select("id", "userName").eq("userType", userType).in("id", userIds));
    }

    /**
     * 根据用户查询学分
     */
    public EntityMap findByUser(Long userId) {
    CriteriaQuery queryWrapper = new CriteriaQuery<EntityMap>(new PagerInfo());
    queryWrapper.select("cb.*,u.email,u.userName,u.sex,u.mobile,u.birthday,u.address,u.company,u.deptName,u.positionName,u.qq");
    queryWrapper.eq("u.id", userId);
    queryWrapper.createAlias("creditbank", "cb");
    PqGrid pqGrid = pageList(queryWrapper);
    if (pqGrid.getRows().size() > 0) {
    return (EntityMap) pqGrid.getRows().get(0);
    }
    return new EntityMap();
    }


    /**
     * 根据用户
     */
    public List<String> selectAllCompany(){
    return listObjs(q().isNotNull("companyId").eq("status", 1),e-> e.toString());
    }

    /**
     * 根据部门查询对应的用户
     */
    public List<String> selectByDept(String[] deptIds){
    return listObjs(q().in("deptId", deptIds), e-> e.toString());
    }

    /**
     * 统计某几个部门人数
     */
    public Integer countByDept(List<Long> deptIds){
    return count(q().eq(true, "userType", "UT_STUDENT").in(true, "deptId", deptIds));
    }

    /**
     * 添加员工
     */
    @Override
    public boolean addStaffs(SysUserDto user,Long companyId){
    SysCompany company = companyService.getById(companyId);
    //根据手机号查询用户是否存在
    SysUser staff = findByMobile(user.getMobile());
    if(ObjectUtils.isNotEmpty(staff)){
    Long userCompanyId = staff.getCompanyId();
    if(ObjectUtils.isNotEmpty(userCompanyId)){
    return true;
    }
    }
    //查询该企业员工数量
    Integer staffNum = count(q().eq("companyId", company.getId()));
    Integer staffNumCompany = ObjectUtils.gertIngeter(company.getStaffNum(), 0);
    if (staffNum >= staffNumCompany) {
    return false;
    }
    if (ObjectUtils.isNotEmpty(staff)) {//根据手机号查询到员工
    staff.setJobNo(user.getJobNo());
    staff.setCompanyId(company.getId());
    staff.setUserName(user.getUserName());
    staff.setIdCard(user.getIdCard());
    boolean a = saveOrUpdate(staff);
    return a;
    }
    //创建账号
    user.setCompanyId(company.getId());
    user.setPassword(CommonConstants.DEF_PWD);
    user.setUserType("UT_STUDENT");
    Boolean tag = accountService.register(user);
    if (tag) {//创建账号成功初始化
    staff = findByMobile(user.getMobile());
    SysBalance balance = balanceService.findByUser(user.getId());
    if (ObjectUtils.isEmpty(balance)) {
    balanceService.insert(staff.getId());
    }
    Integer num = userabilityService.countByUser(staff.getId());
    if (num < 1) {
    //初始化段位等级
    userabilityService.initUserability(staff.getId());
    }
    }
    return tag;
    }

    @Override
    public SysUser findByIdCard(String idCard){
    return getOne(q().eq("idCard", idCard), false);
    }

    }

